package safe_lru

import (
	"fmt"
	"sync"
	"testing"
)

type String string

func (s String) Len() int64 {
	return int64(len(s))
}

// TestCache_ConcurrentDelete 测试并发删除操作
func TestCache_ConcurrentDelete(t *testing.T) {
	lruCache := New(int64(10000), nil)

	// 初始化数据
	for i := 0; i < 20; i++ {
		key := fmt.Sprintf("key%d", i)
		lruCache.Put(key, String(fmt.Sprintf("value%d", i)))
	}

	var wg sync.WaitGroup
	panicCount := 0
	var mu sync.Mutex

	// 并发删除和写入
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func(id int) {
			defer func() {
				if r := recover(); r != nil {
					mu.Lock()
					panicCount++
					mu.Unlock()
					fmt.Printf("Goroutine %d panic: %v\n", id, r)
				}
				wg.Done()
			}()
			key := fmt.Sprintf("key%d", id%20)
			// 删除操作
			lruCache.Delete(key)
			// 立即重新写入
			lruCache.Put(key, String(fmt.Sprintf("newvalue%d", id)))
			// 读取操作
			_, _ = lruCache.Get(key)
		}(i)
	}

	wg.Wait()
	fmt.Printf("Panic count: %d/50\n", panicCount)
}
